//简单但典型的生产者消费者模式

#include <mutex>
#include <queue>
#include <thread>
#include <condition_variable>
#include <iostream>

std::mutex mtx;
std::queue<int> queue;
std::condition_variable notEmpty;
std::condition_variable notFull;

const size_t maxSz = 10;
const size_t taskSz = 100;

void proceducer(){
  for(size_t i = 0; i < taskSz; ++i){
    std::unique_lock<std::mutex> lock(mtx);
    notFull.wait(lock, [&](){return queue.size() < maxSz;});
  	queue.push(i);
    std::cout << " proc " << i << std::endl;
    lock.unlock();
    notEmpty.notify_one(); 
  }
}

void consumer(){
  for(size_t i = 0; i < taskSz; ++i){
    std::unique_lock<std::mutex> lock(mtx);
    notEmpty.wait(lock, [&](){return !queue.empty();});
    auto task = queue.front();
    std::cout << " cos " << queue.front() << std::endl;
    queue.pop();
    lock.unlock();
    notFull.notify_one();
  }
}

int main(){
  std::thread proc(proceducer);
  std::thread cons(consumer);
  proc.join();
  cons.join();
  return 0;
}